<?php

namespace common\models;

use app\models\AdminLog;
use Yii;

/**
 * This is the model class for table "attributes".
 *
 * @property string $id
 * @property string $catalog_id
 * @property string $name
 * @property string $type
 * @property string $type_data
 *
 * @property Catalog $catalog
 * @property PostAttr[] $postAttrs
 */
class Attributes extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'attributes';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['catalog_id', 'name'], 'required'],
            [['catalog_id'], 'integer'],
            [['type', 'type_data'], 'string'],
            [['name'], 'string', 'max' => 64],
//            [['name'], 'unique'],
            [['catalog_id'], 'exist', 'skipOnError' => true, 'targetClass' => Catalog::className(), 'targetAttribute' => ['catalog_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'catalog_id' => '所属栏目',
            'name' => '属性名称',
            'type' => '编辑类型',
            'type_data' => '对应type的数据源（json格式）',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCatalog()
    {
        return $this->hasOne(Catalog::className(), ['id' => 'catalog_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPostAttrs()
    {
        return $this->hasMany(PostAttr::className(), ['attr_id' => 'id']);
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        if ($insert) {
            AdminLog::log("新添内容属性：" . $this->name, "create");
        } else {
            AdminLog::log("更新内容属性：旧：" . $changedAttributes['name'] . "；新：" . $this->name);
        }
    }

    public function afterDelete()
    {
        parent::afterDelete();
        AdminLog::log("删除内容属性：" . $this->name, "delete");
    }
}
